package com.ytclub.subject.domain.handle;

import com.alibaba.fastjson.JSON;
import com.ytclub.subject.common.enums.IsDeletedFlagEnum;
import com.ytclub.subject.common.enums.SubjectInfoTypeEnum;
import com.ytclub.subject.domain.convert.MultipleSubjectConverter;
import com.ytclub.subject.domain.entity.SubjectAnswerBO;
import com.ytclub.subject.domain.entity.SubjectInfoBO;
import com.ytclub.subject.domain.entity.SubjectOptionBO;
import com.ytclub.subject.infra.basic.entity.SubjectMultiple;
import com.ytclub.subject.infra.basic.service.SubjectMultipleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

/**
 * 多选题handler
 *
 * @author: HuangQi
 * @date: Created in 21:55 2023/12/20
 * @description:
 */
@Slf4j
@Component
public class MultipleTypeHandler implements SubjectTypeHandler {

    @Resource
    private SubjectMultipleService subjectMultipleService;

    @Override
    public SubjectInfoTypeEnum getHandlerType() {
        return SubjectInfoTypeEnum.MULTIPLE;
    }

    @Override
    public void add(SubjectInfoBO subjectInfoBO) {
        // 多选题目的插入
        if (log.isInfoEnabled()) {
            log.info("MultipleTypeHandler.add.bo:{}", JSON.toJSONString(subjectInfoBO));
        }

        // 类型转换
        List<SubjectMultiple> subjectMultipleList = new LinkedList<>();
        subjectInfoBO.getOptionList().forEach(Option -> {
            SubjectMultiple subjectMultiple = MultipleSubjectConverter.INSTANCE.convertBoToEntity(Option);
            subjectMultiple.setSubjectId(subjectInfoBO.getId());
            subjectMultiple.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
            subjectMultipleList.add(subjectMultiple);
        });

        // 数据插入
        subjectMultipleService.batchInsert(subjectMultipleList);
    }

    /**
     * 根据题目id查询题目答案
     *
     * @param subjectId 题目id
     * @return 题目答案
     */
    @Override
    public SubjectOptionBO query(Long subjectId) {
        // 根据多选题题目id查询题目答案
        SubjectMultiple subjectMultiple = new SubjectMultiple();
        subjectMultiple.setSubjectId(Long.valueOf(subjectId));
        List<SubjectMultiple> result = subjectMultipleService.queryByCondition(subjectMultiple);

        // 返回多选题答案
        List<SubjectAnswerBO> subjectAnswerBOList = MultipleSubjectConverter.INSTANCE.convertEntityToBoList(result);
        SubjectOptionBO subjectOptionBO = new SubjectOptionBO();
        subjectOptionBO.setOptionList(subjectAnswerBOList);
        return subjectOptionBO;
    }
}
